//
//  ViewController.swift
//  MyPlayground
//
//  Created by 范东 on 2022/5/10.
//

import UIKit
import SwiftSoup
import SDWebImage
import MJRefresh
import Toast
import SnapKit


class ViewController: UIViewController {
    
    
    var dataArray = [ListModel]()
    // current document
    var document: Document = Document.init("")
    var detailDocument: Document = Document.init("")
    var currentUrl = "https://www.appinn.com/category/ios/page/"
    var page = 1
    
    var URLStrings = [String]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        if UIDevice.current.userInterfaceIdiom == .pad {
            view.addSubview(collectionView)
            collectionView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            MJRefreshNormalHeader { [weak self] in
              // load some data
                self?.headerRefresh()
            }.autoChangeTransparency(true)
            .link(to: collectionView)
            MJRefreshBackNormalFooter{ [weak self] in
                // load some data
                  self?.footerRefresh()
              }.autoChangeTransparency(true)
              .link(to: collectionView)
            collectionView.mj_header?.beginRefreshing()
        }else{
            view.addSubview(tableView)
            tableView.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            MJRefreshNormalHeader { [weak self] in
              // load some data
                self?.headerRefresh()
            }.autoChangeTransparency(true)
              .link(to: tableView)
            MJRefreshBackNormalFooter{ [weak self] in
                // load some data
                  self?.footerRefresh()
              }.autoChangeTransparency(true)
              .link(to: tableView)
            tableView.mj_header?.beginRefreshing()
        }
        
    }

    
    func headerRefresh(){
        page = 1
        downloadHTML()
    }
    
    func footerRefresh(){
        page = page + 1
        downloadHTML()
    }
    
    
    func downloadHTML() {
        // url string to URL
        guard let url = URL(string: currentUrl+"\(page)/") else {
            // an error occurred
            view.makeToast("url格式不正确")
            return
        }
        DispatchQueue.global().async {
            do {
                // content of url
                let html = try String.init(contentsOf: url)
                // parse it into a Document
                self.document = try SwiftSoup.parse(html)
                // parse css query
                DispatchQueue.main.async {
                    if self.page == 1 {
                        self.dataArray.removeAll()
                    }
                    self.parse()
                }
            } catch let error {
                // an error occurred
                DispatchQueue.main.async {
                    self.view.makeToast(error.localizedDescription)
                }
            }
        }
        

    }

    //Parse CSS selector
    func parse() {
        do {
            //empty old items
            // firn css selector
            let elements: Elements = try document.select("article")
            //transform it into a local object (Item)
            for element in elements {
                let post_img = try element.getElementsByClass("post-img").first()
                let post_data = try element.getElementsByClass("post-data").first()
                
                let title = try post_data?.getElementsByClass("title post-title").text() ?? ""
                let url = try post_data?.getElementsByClass("title post-title").select("a").attr("href") ?? ""
                let img = try post_img?.getElementsByTag("img").get(0).attr("src") ?? ""
                
                dataArray.append(ListModel(title: title, img: img, url: url))
            }
            if UIDevice.current.userInterfaceIdiom == .pad {
                collectionView.reloadData()
                collectionView.mj_header?.endRefreshing()
                collectionView.mj_footer?.endRefreshing()
            }else{
                tableView.reloadData()
                tableView.mj_header?.endRefreshing()
                tableView.mj_footer?.endRefreshing()
            }

        } catch let error {
            view.makeToast(error.localizedDescription)
        }
        if UIDevice.current.userInterfaceIdiom == .pad {
            collectionView.reloadData()
            collectionView.mj_header?.endRefreshing()
            collectionView.mj_footer?.endRefreshing()
        }else{
            tableView.reloadData()
            tableView.mj_header?.endRefreshing()
            tableView.mj_footer?.endRefreshing()
        }
        
    }

    lazy var tableView: UITableView = {
        let tableView = UITableView(frame: .zero, style: .plain)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.register(ListCell.classForCoder(), forCellReuseIdentifier: "ListCell")
        tableView.separatorStyle = .none
        return tableView
    }()
    
    lazy var collectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(ItemCell.classForCoder(), forCellWithReuseIdentifier: "ItemCell")
        return collectionView
    }()
    
}

extension ViewController: UITableViewDelegate,UITableViewDataSource{
    func numberOfSections(in tableView: UITableView) -> Int {
        1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        dataArray.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "ListCell", for: indexPath) as! ListCell
        if indexPath.row < dataArray.count {
            let model = dataArray[indexPath.row]
            cell.model = model
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        let model = dataArray[indexPath.row]
        return (CGFloat.screenW - 20) * 250 / 390 + 10 + 15 + (model.title as NSString).boundingRect(with: CGSize(width: .screenW - 20, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: [.font: UIFont.systemFont(ofSize: 15)], context: nil).size.height
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        gotoSafari(url: dataArray[indexPath.row].url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    }
}

extension ViewController: UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        dataArray.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ItemCell", for: indexPath) as! ItemCell
        if indexPath.item < dataArray.count {
            let model = dataArray[indexPath.item]
            cell.model = model
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: floor((.screenW - 5 * 20 ) / 4), height: 200)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        20
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        20
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        gotoSafari(url: dataArray[indexPath.row].url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    }
}
